import CommonTable from '@/components/CommonTable';
import { Button, Space } from 'antd';
import { useState } from 'react';
import SaveStation from './SaveStation';
import styles from './Stations.less';

const Stations = (props) => {
  const { type, dataSource, onChange } = props;
  const [mode, setMode] = useState('list');
  const [record, setRecord] = useState();
  const columns = [
    {
      title: '序号',
      dataIndex: 'number',
      width: 65,
      fixed: 'left',
      render: (text, record, index) => index + 1,
    },
    {
      title: '充电站',
      dataIndex: 'chargeStationName',
      ellipsis: true,
      width: 240,
    },
    {
      title: '距离下一站时间（分）',
      dataIndex: 'nextTimes',
      width: 175,
      align: 'center',
    },
    {
      title: '到下一站距离（km）',
      dataIndex: 'nextMileages',
      width: 170,
      align: 'center',
    },
    {
      title: '操作',
      dataIndex: 'operate',
      width: 100,
      fixed: 'right',
      render: (text, record, index) => {
        return (
          <Space>
            <a
              onClick={() => {
                setRecord(record);
                setMode('edit');
              }}
            >
              编辑
            </a>
            <a
              onClick={() => {
                const result = [...dataSource];
                result.splice(index, 1);
                onChange?.(result);
              }}
            >
              删除
            </a>
          </Space>
        );
      },
    },
  ];
  const handleOk = (values) => {
    if (record) {
      onChange?.(
        dataSource.map((item) => {
          if (
            (record.stationId && item.stationId === record.stationId) ||
            item.__key === record.__key
          ) {
            return {
              ...item,
              ...values,
            };
          }
          return item;
        }),
      );
    } else {
      onChange?.([
        ...dataSource,
        {
          ...values,
          __key: new Date().getTime(),
        },
      ]);
    }
    setMode('list');
    setRecord();
  };
  console.log('dataSource', dataSource);
  return (
    <div className={styles.stations}>
      <header className={styles.header}>
        {{ 0: '空载', 1: '重载' }[type]}
      </header>
      <div className={styles.operation}>
        <Button type="primary" size="small" onClick={() => setMode('add')}>
          添加
        </Button>
      </div>
      <section className={styles.section}>
        <CommonTable
          rowKey="stationId"
          pagination={false}
          columns={columns}
          dataSource={dataSource}
        />
      </section>
      <SaveStation
        open={['add', 'edit'].includes(mode)}
        record={record}
        onClose={() => {
          setMode('list');
          setRecord();
        }}
        onOk={handleOk}
      />
    </div>
  );
};

export default Stations;
